﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Active.Core;
namespace Active.Controls
{
    public class CustomerBill : Control
    {
        #region Properties
        private string _CssClass = "";
        /// <summary>
        /// 样式
        /// </summary>
        public string CssClass
        {
            get { return _CssClass; }
            set { _CssClass = value; }
        }

        private Bill _CurrentBill = null;
        /// <summary>
        /// 当前Bill
        /// </summary>
        public Bill CurrentBill
        {
            get
            {
                if (_CurrentBill == null)
                {
                    _CurrentBill = GetBill();
                }
                return _CurrentBill;
            }
        }

        #region Business Methods

        protected Bill GetBill()
        {
            string idString;
            if (IsPager)
                idString = Page.Request.QueryString["customerBillId"];
            else
                idString = Page.Request.QueryString["id"];
            object businessObj = Page.Session["CurrentObj"];
            if (businessObj == null || !(businessObj is Bill)
                || (!Page.IsPostBack && !((Bill)businessObj).Id.ToString().Equals(idString)))
            {
                try
                {
                    if (!string.IsNullOrEmpty(idString))
                    {
                        businessObj = Bill.GetBill(int.Parse(idString));
                    }
                    else
                    {
                        //businessObj = Bill.NewBill();
                        businessObj = null;
                    }
                    Page.Session["CurrentObj"] = businessObj;
                }
                catch (System.Security.SecurityException)
                {
                    Page.Response.Redirect("~/Bill");
                }
            }
            return businessObj as Bill;
        }

        #endregion

        private Orders _CurrentOrders;
        /// <summary>
        /// 当前Bill的所以Orders
        /// </summary>
        private Orders CurrentOrders
        {
            get
            {
                if (CurrentBill == null)
                    return null;
                return CurrentBill.Orders;
            }
        }

        private decimal _TotalRealIncome = 0;
        /// <summary>
        /// 总收入
        /// </summary>
        /// <returns></returns>
        private decimal TotalRealIncome
        {
            get { return _TotalRealIncome; }
            set { _TotalRealIncome = value; }
        }

        private decimal _TotalFinalRealIncome = 0;
        /// <summary>
        /// 实总收入
        /// </summary>
        private decimal TotalFinalRealIncome
        {
            get { return _TotalFinalRealIncome; }
            set { _TotalFinalRealIncome = value; }
        }

        private decimal _TotalPayOut = 0;
        /// <summary>
        /// 总支出
        /// </summary>
        /// <returns></returns>
        private decimal TotalPayOut
        {
            get { return _TotalPayOut; }
            set { _TotalPayOut = value; }
        }

        private decimal _TotalBrokerage = 0;
        /// <summary>
        /// 订单所用的反点数
        /// </summary>
        private decimal TotalBrokerage
        {
            get { return _TotalBrokerage; }
            set { _TotalBrokerage = value; }
        }
        private int _MainRowsCount = CompanySettings.Instance.BalanceBillMainRows;
        /// <summary>
        /// 客户订单行数
        /// </summary>
        public int MainRowsCount
        {
            get { return _MainRowsCount; }
            set { _MainRowsCount = value; }
        }
        private int _BalanceBillRowCount = 0;
        /// <summary>
        /// 平衡表总行数
        /// </summary>
        private int BalanceBillRowCount
        {
            get
            {
                if (_BalanceBillRowCount == 0)
                    _BalanceBillRowCount = GetCustomerBillRowCount(); //需要修改
                return _BalanceBillRowCount;
            }

        }
        private int _PageCount = 0;
        /// <summary>
        /// 总页数
        /// </summary>
        private int PageCount
        {
            get
            {
                if (_PageCount == 0)
                {
                    if (BalanceBillRowCount % MainRowsCount == 0)
                        _PageCount = BalanceBillRowCount / MainRowsCount;
                    else
                        _PageCount = BalanceBillRowCount / MainRowsCount + 1;
                }
                return _PageCount;
            }
        }
        private bool _IsPager = false;
        /// <summary>
        /// 是否分页
        /// </summary>
        public bool IsPager
        {
            get { return _IsPager; }
            set { _IsPager = value; }
        }
        private int ps = 1;
        #endregion

        #region mathod
        private int GetCustomerBillRowCount()
        {
            int rowCount = 0;
            foreach (Order order in CurrentBill.Orders)
            {
                foreach (CustomerOrder co in order.CustomerOrders)
                {
                    rowCount++;
                }
            }
            return rowCount;
        }
        /// <summary>
        /// 输出客户Order
        /// </summary>
        /// <param name="order"></param>
        private void WriteCustomerInfo(CustomerOrder customerOrder, HtmlTextWriter writer)
        {
            TotalRealIncome += customerOrder.Payout;
            TotalFinalRealIncome += customerOrder.RealPayout;
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (customerOrder.Category == OrderType.Pay)
            {
                if(customerOrder.UnitPrice>0)
                writer.Write(customerOrder.UnitPrice.ToString("c2"));
                else
                writer.Write(" ");
            }
            else
            {
                writer.Write(Formater.Translate(customerOrder.Category.ToString()));
            }

            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write(customerOrder.Times.ToString());
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            double customerOrderFinalDiscount = customerOrder.RealDiscount * 100;
            if (customerOrder.Category == OrderType.Additional)
                writer.Write("-");
            else
                writer.Write(customerOrderFinalDiscount>0?customerOrderFinalDiscount.ToString() + "%":"-");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (customerOrder.Category == OrderType.Pay || customerOrder.Category == OrderType.Additional)
            {
                if (customerOrder.RealPayout>0)
                writer.Write(customerOrder.RealPayout.ToString("c2"));
                else
                writer.Write(" ");
            }
            else if (customerOrder.Category == OrderType.Series)
            {
                writer.Write("套播");
            }
            else if (customerOrder.Category == OrderType.Present)
            {
                writer.Write("赠送");
            }
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            double orderDiscount = customerOrder.Discount * 100;
            if (customerOrder.Category == OrderType.Additional)
                writer.Write("-");
            else
                writer.Write(orderDiscount>0?orderDiscount.ToString() + "%":"-");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (customerOrder.Category == OrderType.Pay || customerOrder.Category == OrderType.Additional)
                writer.Write(customerOrder.Payout>0?customerOrder.Payout.ToString("c2"):" ");
            else 
            {
                writer.Write(Formater.Translate(customerOrder.Category.ToString()));
            }
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            string cusDiscription = customerOrder.Description;
            //if (string.IsNullOrEmpty(cusDiscription))
            //{
            //    cusDiscription = "无备注";
            //}
            writer.Write(cusDiscription);
            writer.RenderEndTag();
        }

        /// <summary>
        /// 输出固定列,值
        /// </summary>
        /// <param name="txt"></param>
        /// <param name="count"></param>
        private void WriteNull(string txt, int count, HtmlTextWriter writer)
        {
            for (int i = 0; i < count; i++)
            {
                writer.AddAttribute("class", "redtext");
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.Write(txt);
                writer.RenderEndTag();
            }
        }
        /// <summary>
        /// 一对多,或一对一,一对无
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="writer"></param>
        private void OneToMore(Order order, HtmlTextWriter writer)
        {
            if (order.CustomerOrders != null && order.CustomerOrders.Count > 0)
            {
                foreach (CustomerOrder customerOrder in order.CustomerOrders)
                {
                    writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                    writer.RenderBeginTag(HtmlTextWriterTag.Td);
                    string strNameAndChannel = (order.Media.Name == customerOrder.Channel) ? customerOrder.Channel : order.Media.Name + "<br/>" + customerOrder.Channel;
                    writer.Write(strNameAndChannel);
                    writer.RenderEndTag();
                    WriteCustomerInfo(customerOrder, writer);
                    writer.RenderEndTag();
                    if (ps % MainRowsCount == 0 && IsPager)
                    {
                        WriteEndTable(false, ps / MainRowsCount, writer);
                        WriteStartTable(ps / MainRowsCount + 1, writer);
                    }
                    ps++;
                }

            }
            else
            {

                writer.RenderBeginTag(HtmlTextWriterTag.Tr);
                writer.RenderBeginTag(HtmlTextWriterTag.Td);
                writer.Write(order.Media.Name);
                writer.RenderEndTag();
                WriteNull(" ", 7, writer);
                writer.RenderEndTag();
            }


        }
        /// <summary>
        /// WriteTable
        /// </summary>
        /// <param name="Orders"></param>
        /// <param name="pageNo"></param>
        /// <param name="writer"></param>
        private void WriteTable(Orders Orders, HtmlTextWriter writer)
        {
            #region Table

            WriteStartTable(1, writer);

            #region TableBody
            foreach (Order order in Orders)
            {
                OneToMore(order, writer);
            }
            #endregion

            WriteEndTable(true, PageCount, writer);


            #endregion
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="writer"></param>
        private void WriteStartTable(int pageNo, HtmlTextWriter writer)
        {
            writer.AddAttribute("id", "printDiv" + pageNo.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            if (CssClass != "")
                writer.AddAttribute("class", CssClass);
            else
                writer.AddAttribute("class", "normal");
            writer.AddAttribute("id", "printTable");
            writer.RenderBeginTag(HtmlTextWriterTag.Table);
            #region 第一行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("colspan", "8");
            writer.AddAttribute("class", "fontLarger noneborder");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户表");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("colspan", "3");
            writer.AddAttribute("class", "noneborder left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("投放日期： " + CurrentBill.StartDate.Date.ToShortDateString() + "~" + CurrentBill.EndDate.Date.ToShortDateString());
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "3");
            writer.AddAttribute("class", "noneborder left");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户： " + CurrentBill.Customer.Name);
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.AddAttribute("class", "noneborder right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("编号:" + CurrentBill.Number + "(" + pageNo.ToString() + "/" + PageCount.ToString() + ")");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();
            #endregion

            #region 第二行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            writer.AddAttribute("rowspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("媒体");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("报价");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("实收客户");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("应收客户");
            writer.RenderEndTag();
            //
            writer.AddAttribute("rowspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户部备注");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();
            #endregion

            #region 第三行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("单价");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("次数");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("优惠率");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("实收");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("优惠率");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("应收");
            writer.RenderEndTag();
            //EndRow
            writer.RenderEndTag();
            #endregion
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isWriteTotal"></param>
        /// <param name="writer"></param>
        private void WriteEndTable(bool isWriteTotal, int pageNo, HtmlTextWriter writer)
        {
            #region 合计行...
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("colspan", "3");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("合计:");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (isWriteTotal)
                writer.Write(TotalFinalRealIncome>0?TotalFinalRealIncome.ToString("c"):" ");
            else
                writer.Write("见最后页"); ;
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            if (isWriteTotal)
                writer.Write(TotalRealIncome>0?TotalRealIncome.ToString("c"):" ");
            else
                writer.Write("见最后页");
            writer.RenderEndTag();
            //
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //EndTr
            writer.RenderEndTag();
            #endregion

            #region 签名行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户部:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("执行总监:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "4");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //EndTr
            writer.RenderEndTag();
            #endregion

            #region 签名行
            writer.RenderBeginTag(HtmlTextWriterTag.Tr);
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("客户经理:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "2");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //
            writer.AddAttribute("class", "right");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.Write("总经理:");
            writer.RenderEndTag();
            //
            writer.AddAttribute("colspan", "4");
            writer.RenderBeginTag(HtmlTextWriterTag.Td);
            writer.RenderEndTag();
            //EndTr
            writer.RenderEndTag();
            #endregion
            //EndTable
            writer.RenderEndTag();
            //EndDiv
            writer.RenderEndTag();
            //打印按钮
            writer.AddAttribute("type", "button");
            writer.AddAttribute("class", "button");
            if (IsPager)
            {
                writer.AddAttribute("value", "打印第" + pageNo.ToString() + "页");
                writer.AddAttribute("onclick", string.Format("javascript:window.open('{0}')", Utils.RelativeWebRoot + "Print.aspx?id=" + "printDiv" + pageNo.ToString()));
            }
            else
            {
                writer.AddAttribute("value", "打   印");
                if (PageCount == 1)
                    writer.AddAttribute("onclick", string.Format("javascript:window.open('{0}')", Utils.RelativeWebRoot + "Print.aspx?id=" + "printDiv" + pageNo.ToString()));
                else if (PageCount > 1)
                {
                    writer.AddAttribute("onclick", string.Format("javascript:window.open('{0}')", Utils.RelativeWebRoot + "PrintPager.aspx?customerBillId=" + CurrentBill.Id.ToString()));
                }
            }
            writer.RenderBeginTag(HtmlTextWriterTag.Input);
            writer.RenderEndTag();
        }

        #endregion

        #region override
        protected override void Render(HtmlTextWriter writer)
        {
            if (CurrentOrders == null || CurrentOrders.Count == 0)
            {
                writer.AddAttribute("style", "color:Red; font-size:x-large;");
                writer.RenderBeginTag(HtmlTextWriterTag.Div);
                if (!IsPager)
                    writer.Write("该清单无任何订单");
                writer.RenderEndTag();
                return;
            }


            WriteTable(CurrentOrders, writer);


        }
        #endregion
    }
}
